package com.arcvideo.acsplayer.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.URLUtil;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.arcvideo.MediaPlayer.ArcMediaPlayer;
import com.arcvideo.MediaPlayer.MV2Config;
import com.arcvideo.MediaPlayer.MV2Config.MEDIAFILE;
import com.arcvideo.acsplayer.R;
import com.arcvideo.acsplayer.app.AcsPlayerApplication;
import com.arcvideo.acsplayer.config.PlayConfig.AMMF_STATE;
import com.arcvideo.acsplayer.config.PlayConfig.SCREEN_STATE;
import com.arcvideo.acsplayer.data.AcsPlayerData;
import com.arcvideo.acsplayer.dialog.NormalDialog;
import com.arcvideo.acsplayer.dialog.ProgressDialog;
import com.arcvideo.acsplayer.mode.ArclouldVideoInfo;
import com.arcvideo.acsplayer.mode.InputVideoInfo;
import com.arcvideo.acsplayer.mode.LocalVideoInfo;
import com.arcvideo.acsplayer.mode.TranscodedVideoInfo;
import com.arcvideo.acsplayer.utils.DensityUtil;
import com.arcvideo.acsplayer.utils.LogUtil;
import com.arcvideo.acsplayer.utils.NetUtil;
import com.arcvideo.acsplayer.utils.SystemUtil;
import com.arcvideo.acsplayer.utils.UriUtil;
import com.arcvideo.acsplayer.widget.BrightnessView;
import com.arcvideo.acsplayer.widget.FastMoveView;
import com.arcvideo.acsplayer.widget.FastMoveView.FastMoveInterface;
import com.arcvideo.acsplayer.widget.GyroHDControlView;
import com.arcvideo.acsplayer.widget.GyroHDControlView.GyroHDControlInterface;
import com.arcvideo.acsplayer.widget.HDselectView;
import com.arcvideo.acsplayer.widget.HDselectView.SelectInterface;
import com.arcvideo.acsplayer.widget.PlayAgainView;
import com.arcvideo.acsplayer.widget.PlayAgainView.PlayAgainControlInterface;
import com.arcvideo.acsplayer.widget.PlayControlView;
import com.arcvideo.acsplayer.widget.PlayControlView.PlayControlInterface;
import com.arcvideo.acsplayer.widget.TitleView;
import com.arcvideo.acsplayer.widget.TitleView.TitleInterface;
import com.arcvideo.acsplayer.widget.VolumeView;
import com.arcvideo.vrkit.VRConst.ControlMode;
import com.arcvideo.vrkit.VRConst.RenderMode;
import com.arcvideo.vrkit.VRVideoView;
import com.arcvideo.vrkit.VRVideoView.OnScaleChangedListener;

@SuppressLint("NewApi")
public class PlayActivity extends BaseActivity implements OnClickListener, OnScaleChangedListener {
	private static String TAG = PlayActivity.class.getSimpleName();

	// 控件
	private NormalDialog mRemandDialog = null;
	//private AlertDialog mRemandDialog = null;
	private TitleView mTitleContorl = null;
	private VolumeView mVolumeControl = null;
	private BrightnessView mBrihtnessControl = null;
	private HDselectView mHDSelectControl = null;
	private FastMoveView mFastMoveControl = null;
	private PlayControlView mPlayControl = null;
	private PlayAgainView mPlayAgainControl = null;
	private GyroHDControlView mGyroHDControl = null;
	private Dialog mBufferingProgress = null;
	private ProgressDialog mLoadingDialog = null;

	private int mDialogType = 0;
	private boolean mIsVRMode = false;
	private String mQualityState = HDselectView.STATE_HD;
	private boolean mbGyroOpen = true;
	private boolean mbDualOpen = false;
	private SCREEN_STATE mScreenState = SCREEN_STATE.PORTRAIT_SCREEN;

	// 手势处理
	private static final int GESTURE_MODIFY_NONE = 0;
	private static final int GESTURE_MODIFY_PROGRESS = 1;
	private static final int GESTURE_MODIFY_VOLUME = 2;
	private static final int GESTURE_MODIFY_BRIGHT = 3;

	private static final int STEP_PROGRESS = 3;
	private static final int STEP_VOLUME = 3;
	private static final int STEP_BRIGHT = 3;

	private static final int MIN_DISTANCE = 5;

	private boolean mbGestrueProgress = false;
	private boolean mbGestrueVolume = false;
	private boolean mbGestrueBright = false;
	private boolean mbGestrueGyroHD = false;
	private boolean mbGestrueHDSelect = false;
	private boolean mbGestruePlay = false;

	private GestureDetector mGestureDetector;
	private int mGestureTag = 0;
	private boolean mbFirstScroll = false;
	private int mWindowWidth = 0;
	private int mWindowHeight = 0;

	// 播放相关
	public static final int FROM_URL_INPUT = 1;
	public static final int FROM_LOCAL = 2;
	public static final int FROM_ARCLOULD = 3;
	public static final int FROM_LAST_PLAYED = 4;

	public static final String URLDATA = "url_data";
	public static final String URLTYPE = "url_type";
	public static final String URLINDEX = "url_index";

	public ArrayList<InputVideoInfo> mInputVideoInfoList = null;
	private ArrayList<LocalVideoInfo> mLocalVideoList = null;
	private LocalVideoInfo mCurrentLocalVideo = null;
	private ArrayList<ArclouldVideoInfo> mArclouldVideoList = null;
	private ArclouldVideoInfo mCurrentArclouldVideo = null;
	private TranscodedVideoInfo mCurrentTranscodedVideoInfo = null;
	private String mUrl = null;
	private Uri m_uri = null;
	private int mCurrentPlayType = FROM_URL_INPUT;
	private int mCurrentPlayIndex = 0;

	private static final int SEEK_STEP = 5000;

	private AMMF_STATE m_PlayerState = AMMF_STATE.IDLE;
	protected ArcMediaPlayer mMediaPlayer;

	private VRVideoView m_TextureView = null;
	private SurfaceView m_surfaceView = null;
	private SurfaceHolder mSurfaceHolder = null;
	private boolean mIsSurfaceCreated = false;

	private boolean m_bBuffering = false;
	private boolean m_bVideoSizeChanged = false;

	private int mGestureCurrentPosition = 0;
	private int mCurrentPosition = 0;
	private int mDuration = -1;

	int m_nRotation = 0;
	int mConnectTimeout = 5;
	int mReceiveTimeout = 10;
	int mReconnectCount = 0;

	int m_pixelFormat = android.graphics.PixelFormat.YCbCr_420_SP;

	int m_surfaceType = android.view.SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS;

	int m_nClipWidth = 0;
	int m_nClipHeight = 0;

	int m_frameWidth = 0;
	int m_frameHeight = 0;

	/**
	 * 消息处理
	 */
	// 播放器消息
	public static final int MSG_GET_POSITION = 1;
	public static final int MSG_GET_BUFFERINGPERCENT = 2;
	public static final int MSG_DELAYED_OPEN_EXT = 3;
	public static final int MSG_DELAYED_OPEN = 4;
	public static final int MSG_DELAYED_OPEN_DELAY = 500;

	// 控件消息
	private static final int MSG_HIDE_CONTROL_BAR = 11;
	private static final int MSG_SHOW_CONTROL_BAR = 12;
	private static final int MSG_HIDE_POP_BAR = 13;
	private static final int MSG_SHOW_CONTROL_BAR_DELAY = 3;
	private static final int MSG_HIDE_CONTROL_BAR_DELAY = 4000;
	private static final int MSG_HIDE_POP_BAR_DELEY = 300;
	private static final int MSG_HIDE_POP_BAR_DELEY2 = 3000;



	//鉴权，填上获取到值给accessKey、secret和appKey
	private String accessKey = "cb170875-15d";
	private String secret = "4FTxLuDSQBK5UdU5SwIb";
	private String appKey = "cc904d8aab644b2184e933ea645b40a0";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为无标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 设置为全屏模式
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.activity_play);

		initUi();
		initData();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.id_title_left_btn :
				BrightnessView.startAutoBrightness(getApplicationContext());
				stopPlayback();
				finish();
				break;
			default :
				break;
		}
	}

	@Override
	public void onBackPressed() {
		BrightnessView.startAutoBrightness(getApplicationContext());
		stopPlayback();
		finish();
		super.onBackPressed();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (mIsVRMode) {
			if (!mbGyroOpen)
				m_TextureView.onTouchEvent(event);
		}
		if (mGestureDetector.onTouchEvent(event))
			return true;
		LogUtil.d(TAG, "onTouchEvent event.getAction() = " + event.getAction());
		// 处理手势结束
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_UP :
				if (mIsVRMode) {
					if (mbGestruePlay) {
						endGesture();
						mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
						mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_SHOW_CONTROL_BAR_DELAY);
					} else {
						mDismissHandler.removeMessages(MSG_SHOW_CONTROL_BAR);
						mDismissHandler.sendEmptyMessageDelayed(MSG_SHOW_CONTROL_BAR, MSG_SHOW_CONTROL_BAR_DELAY);
					}
					return false;
				}

				LogUtil.d(TAG, "onTouchEvent mGestureTag = " + mGestureTag);
				if (mGestureTag == GESTURE_MODIFY_PROGRESS) {
					LogUtil.d(TAG, "GESTURE_MODIFY_PROGRESS mCurrentPosition = " + mCurrentPosition);
					mCurrentPosition = mGestureCurrentPosition;
					mMediaPlayer.seekTo(mCurrentPosition);
					// mPlayControl.setCurrentPosition(mCurrentPosition);
					// mPlayControl.setDuration(mDuration);
					mRefreshHandler.sendEmptyMessage(MSG_GET_POSITION);
				}
				mGestureTag = GESTURE_MODIFY_NONE;
				endGesture();

				if (mbGestruePlay) {
					mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
					mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_SHOW_CONTROL_BAR_DELAY);
				} else {
					mDismissHandler.removeMessages(MSG_SHOW_CONTROL_BAR);
					mDismissHandler.sendEmptyMessageDelayed(MSG_SHOW_CONTROL_BAR, MSG_SHOW_CONTROL_BAR_DELAY);
				}
				break;
		}

		return super.onTouchEvent(event);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		if (newConfig.orientation != m_nRotation) {
			m_nRotation = newConfig.orientation;
			mScreenState = getScreenState();
			if (!mIsVRMode) {
				reloadUi();

				videoSizeChanged(mMediaPlayer, m_frameWidth, m_frameHeight);
			} else {
				if (mScreenState == SCREEN_STATE.LANDSCAPE_SCREEN)
					reloadUi();
				switchVRMode();
			}
		}

		super.onConfigurationChanged(newConfig);

	}


	@Override
	protected void onPause() {
		if (mMediaPlayer != null && m_PlayerState == AMMF_STATE.STARTED) {
			mMediaPlayer.pause();
			mCurrentPosition = mMediaPlayer.getCurrentPosition();
			mRefreshHandler.removeMessages(MSG_GET_POSITION);
			m_PlayerState = AMMF_STATE.PAUSED;
			mIsSurfaceCreated = false;
		}

		if (!mIsVRMode) {
			mMediaPlayer.setDisplay(null);
		} else {
			m_TextureView.setMediaPlayer(null);
		}
		setVideoVisible(false);

		super.onPause();
	}

	@Override
	public void onResume() {
		setVideoVisible(true);
		if (!mIsVRMode) {
			if (mIsSurfaceCreated) {
				mSurfaceHolder = m_surfaceView.getHolder();
				mMediaPlayer.setDisplay(mSurfaceHolder);
			}
		} else {
			m_TextureView.setMediaPlayer(mMediaPlayer);
		}

		if (mMediaPlayer != null && m_PlayerState == AMMF_STATE.PAUSED) {
			mMediaPlayer.start();
			mMediaPlayer.seekTo(mCurrentPosition);
			mRefreshHandler.sendEmptyMessage(MSG_GET_POSITION);
			m_PlayerState = AMMF_STATE.STARTED;
		}
		super.onResume();
	}


	@Override
	public void onScaleChanged(float newScale) {
		// TODO Auto-generated method stub

	}

	/**
	 * 初始化UI
	 */
	private void initUi() {
		int orientation = getResources().getConfiguration().orientation;

		mTitleContorl = (TitleView) findViewById(R.id.control_title);
		mTitleContorl.init(orientation, R.drawable.btn_back, R.drawable.btn_vr, R.drawable.btn_setting, mIsVRMode, mTitleInterface);

		mVolumeControl = (VolumeView) findViewById(R.id.control_volume);
		mVolumeControl.hide();

		mBrihtnessControl = (BrightnessView) findViewById(R.id.control_brightness);
		mBrihtnessControl.setActivity(this);
		mBrihtnessControl.hide();

		mHDSelectControl = (HDselectView) findViewById(R.id.control_hdselect);
		mHDSelectControl.init(getResources().getConfiguration().orientation, HDselectView.STATE_ULTRA_CLEAR, mSelectInterface);
		mHDSelectControl.hide();

		mFastMoveControl = (FastMoveView) findViewById(R.id.control_fastmove);
		mFastMoveControl.init(getResources().getConfiguration().orientation, FastMoveView.STATE_BACKWORD, mIsVRMode, mFaceMoveInterface);
		mFastMoveControl.hide();

		mPlayControl = (PlayControlView) findViewById(R.id.control_play);
		mPlayControl.init(getResources().getConfiguration().orientation, mIsVRMode, mPlayControlInterface);
		if (mDuration > 0) {
			mPlayControl.setDuration(mDuration);
		}

		mPlayAgainControl = (PlayAgainView) findViewById(R.id.control_playagain);
		mPlayAgainControl.init(mPlayAgainControlInterface);

		mGyroHDControl = (GyroHDControlView) findViewById(R.id.control_gyrohd);
		mGyroHDControl.init(getResources().getConfiguration().orientation, mIsVRMode, mGyroHDControlInterface);
		mGyroHDControl.hide();

		mLoadingDialog = ProgressDialog.createDialog(this);
		mLoadingDialog.setMessage(getString(R.string.buffering));

		mGestureDetector = new GestureDetector(this, new PlayGestureListener());

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		mWindowWidth = dm.widthPixels;
		mWindowHeight = dm.heightPixels;

		initPlayer();
	}

	/**
	 * 重新加載UI
	 */
	public void reloadUi() {
		int orientation = getResources().getConfiguration().orientation;
		if (null != mFastMoveControl) {
			mFastMoveControl.reload(orientation, mIsVRMode);
		}
		if (null != mHDSelectControl) {
			mHDSelectControl.reload(orientation);
		}
		if (null != mPlayControl) {
			mPlayControl.reload(orientation, mIsVRMode);
		}
		if (null != mTitleContorl) {
			mTitleContorl.reload(orientation, mIsVRMode);
		}
		updadeControlState();
	}

	/**
	 * 初始化播放器
	 */
	public void initPlayer() {
		initPlaySurfaceView();
		if (null == mMediaPlayer) {
			mMediaPlayer = new ArcMediaPlayer();
			mMediaPlayer.validate(this, accessKey, secret, appKey);
			mMediaPlayer.setConfigFile(this, getFilesDir().getAbsolutePath() + "/MV3Plugin.ini");
			mMediaPlayer.reset();
		}
	}

	/**
	 * 初始化surface
	 */
	private void initPlaySurfaceView() {
		initSurfaceType();

		m_surfaceView = (SurfaceView) findViewById(R.id.PorView);
		m_TextureView = (VRVideoView) findViewById(R.id.textureView);
		if (mIsVRMode) {
			m_surfaceView.setVisibility(View.INVISIBLE);
			m_TextureView.setVisibility(View.VISIBLE);
			m_TextureView.setOnScaleChangedListener(this);
			m_TextureView.setKeepScreenOn(true);
			m_TextureView.setControlMode(mControlMode);
			m_TextureView.setRenderMode(mRenderMode);
		} else {
			m_surfaceView.setVisibility(View.VISIBLE);
			m_TextureView.setVisibility(View.INVISIBLE);
		}

		mSurfaceHolder = m_surfaceView.getHolder();
		if (mSurfaceHolder != null) {
			mSurfaceHolder.setType(m_surfaceType);
			mSurfaceHolder.setFormat(m_pixelFormat);
			mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {

				@Override
				public void surfaceDestroyed(SurfaceHolder holder) {
					if (mMediaPlayer != null)
						mMediaPlayer.setDisplay(null);
				}

				@Override
				public void surfaceCreated(SurfaceHolder holder) {
					mIsSurfaceCreated = true;
					if (mMediaPlayer != null)
						mMediaPlayer.setDisplay(m_surfaceView.getHolder());
					videoSizeChanged(mMediaPlayer, mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight());
				}

				@Override
				public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
				}
			});
		}
	}


	/**
	 * 设置surface Tpye
	 */
	private void initSurfaceType() {
		if (Integer.valueOf(android.os.Build.VERSION.SDK) < 14) {
			m_pixelFormat = android.graphics.PixelFormat.RGBA_8888;
			m_surfaceType = android.view.SurfaceHolder.SURFACE_TYPE_NORMAL;//
		} else {
			m_pixelFormat = android.graphics.PixelFormat.YCbCr_420_SP;// YCbCr_420_SP;//
			m_surfaceType = android.view.SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS;//

		}
	}

	/**
	 * 视频宽高设置
	 *
	 * @param mp
	 * @param width
	 * @param height
	 */
	public void videoSizeChanged(ArcMediaPlayer mp, int width, int height) {
		Log.v(TAG, "onVideoSizeChanged called: " + width + "x" + height);

		m_frameWidth = width;
		m_frameHeight = height;
		if (width != 0 && height != 0 && m_PlayerState == AMMF_STATE.STARTED)
			m_bVideoSizeChanged = true;
		Log.v(TAG, "onVideoSizeChanged m_bVideoSizeChanged: " + m_bVideoSizeChanged);
		int nScreenWidth = getWindow().getWindowManager().getDefaultDisplay().getWidth();
		int nScreenHeight = getWindow().getWindowManager().getDefaultDisplay().getHeight();
		float aspect_ratio = mMediaPlayer.getAspectRatio();
		Log.v(TAG, "aspect_ratio=" + aspect_ratio);
		Log.v(TAG, "before adjuct aspect, w=" + m_frameWidth + ",h=" + m_frameHeight);

		if (aspect_ratio != 0.0) {
			m_frameWidth = Float.floatToIntBits((Float.intBitsToFloat(m_frameHeight) * aspect_ratio));

			Log.v(TAG, "after adjuct aspect, w=" + m_frameWidth + ",h=" + m_frameHeight);
		}
		/* start */
		if (m_frameWidth != 0 && m_frameHeight != 0) {
			int estimateW, estimateH;
			if (nScreenWidth * m_frameHeight > nScreenHeight * m_frameWidth) {
				estimateW = nScreenHeight * m_frameWidth / m_frameHeight;
				estimateH = nScreenHeight;
				if (estimateW % 4 != 0)
					estimateW -= estimateW % 4;
			} else {
				estimateW = nScreenWidth;
				estimateH = nScreenWidth * m_frameHeight / m_frameWidth;
				if (estimateH % 4 != 0)
					estimateH -= estimateH % 4;
			}
			int xOffset = (nScreenWidth - estimateW) / 2;
			int yOffset = (nScreenHeight - estimateH) / 2;
			if (xOffset % 4 != 0)
				xOffset -= xOffset % 4;
			if (yOffset % 4 != 0)
				yOffset -= yOffset % 4;
			Log.d(TAG, xOffset + ", " + yOffset + ", " + estimateW + "x" + estimateH);
			if (m_surfaceType == android.view.SurfaceHolder.SURFACE_TYPE_NORMAL) {
				mMediaPlayer.setDisplayRect(xOffset, yOffset, estimateW, estimateH);
				SetSurfaceRect(m_pixelFormat, xOffset, yOffset, estimateW, estimateH);
			} else {
				m_nClipWidth = estimateW;
				m_nClipHeight = estimateH;
				mMediaPlayer.setDisplayRect(xOffset, yOffset, estimateW, estimateH);
				SetSurfaceRect(m_pixelFormat, xOffset, yOffset, estimateW, estimateH);
			}
		} else {
			if (m_surfaceType == android.view.SurfaceHolder.SURFACE_TYPE_NORMAL) {
				mMediaPlayer.setDisplayRect(0, 0, nScreenWidth, nScreenHeight);
				SetSurfaceRect(m_pixelFormat, 0, 0, nScreenWidth, nScreenHeight);
			} else {
				// some implicit rules here..
				mMediaPlayer.setDisplayRect(0, 0, nScreenWidth, nScreenHeight);
				SetSurfaceRect(m_pixelFormat, 0, 0, nScreenWidth, nScreenHeight);
			}
		}
	}

	/**
	 * 设置surface位置大小
	 *
	 * @param PixelFormat
	 * @param x
	 * @param y
	 * @param w
	 * @param h
	 */
	public void SetSurfaceRect(int PixelFormat, int x, int y, int w, int h) {
		RelativeLayout.LayoutParams lp;

		if (w <= 1 && h <= 1) {
			lp = (RelativeLayout.LayoutParams) (mIsVRMode ? m_TextureView.getLayoutParams() : m_surfaceView.getLayoutParams());
			lp.leftMargin = mWindowWidth;
			lp.topMargin = mWindowHeight;
			lp.width = 0;
			lp.height = 0;

			if (mIsVRMode)
				m_TextureView.setLayoutParams(lp);
			else
				m_surfaceView.setLayoutParams(lp);
			LogUtil.d(TAG, "[0]x=" + lp.leftMargin + "y=" + lp.topMargin + "w=" + lp.width + "h=" + lp.height);
		} else {
			LogUtil.d(TAG, "[1]x=" + x + "y=" + y + "w=" + w + "h=" + h);
			lp = (RelativeLayout.LayoutParams) (mIsVRMode ? m_TextureView.getLayoutParams() : m_surfaceView.getLayoutParams());
			LogUtil.d(TAG, "[2]x=" + lp.leftMargin + "y=" + lp.topMargin + "w=" + lp.width + "h=" + lp.height);
			lp.leftMargin = x;
			lp.topMargin = y;
			lp.width = w;
			lp.height = h;

			if (mIsVRMode)
				m_TextureView.setLayoutParams(lp);
			else
				m_surfaceView.setLayoutParams(lp);
			LogUtil.d(TAG, "[3]x=" + lp.leftMargin + "y=" + lp.topMargin + "w=" + lp.width + "h=" + lp.height);
		}

	}

	/**
	 * 保持屏幕常亮
	 *
	 * @param bOn
	 */
	public void KeepScreenOn(boolean bOn) {
		if (mIsVRMode) {
			m_TextureView.setKeepScreenOn(bOn);
		} else {
			SurfaceHolder sfhold;
			sfhold = m_surfaceView.getHolder();
			if (sfhold != null) {
				sfhold.setKeepScreenOn(bOn);
			}
		}
	}

	/**
	 * 隐藏弹出bar
	 */
	private void resetPopBar() {
		mBrihtnessControl.hide();
		mVolumeControl.hide();
		mHDSelectControl.hide();
		mFastMoveControl.hide();
		mGyroHDControl.hide();
		mbGestrueProgress = false;
		mbGestrueVolume = false;
		mbGestrueBright = false;
		mbGestrueGyroHD = false;
		mbGestrueHDSelect = false;
	}

	/**
	 * 检查当前是否有弹出显示框
	 *
	 * @return
	 */
	private boolean checkPopBar() {
		if (!mbGestrueProgress && !mbGestrueVolume && !mbGestrueBright && !mbGestrueGyroHD && !mbGestrueHDSelect)
			return true;
		else
			return false;
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		Intent intent = getIntent();

		mCurrentPlayType = intent.getIntExtra(URLTYPE, FROM_URL_INPUT);
		switch (mCurrentPlayType) {
			case FROM_URL_INPUT :
				mUrl = intent.getStringExtra(URLDATA);
				mInputVideoInfoList = AcsPlayerData.getInstance().getmInputVideoInfoList();
				break;
			case FROM_LOCAL :
				mLocalVideoList = (ArrayList<LocalVideoInfo>) intent.getSerializableExtra(URLDATA);
				mCurrentPlayIndex = intent.getIntExtra(URLINDEX, 0);
				break;
			case FROM_ARCLOULD :
				mArclouldVideoList = (ArrayList<ArclouldVideoInfo>) intent.getSerializableExtra(URLDATA);
				mCurrentPlayIndex = intent.getIntExtra(URLINDEX, 0);
				break;
			case FROM_LAST_PLAYED:
				mUrl = intent.getStringExtra(URLDATA);
			default :
				break;
		}

		getCurrentPlayUrl(mCurrentPlayIndex, mQualityState);
		setTitle();

		if (mCurrentArclouldVideo != null) {
			if (mCurrentArclouldVideo.type == 2) {
				mIsVRMode = false;
			} else if (mCurrentArclouldVideo.type == 1) {
				mIsVRMode = true;
			}
		}


		// 如果是VR模式，则切换到横屏
		if (mIsVRMode) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
			mScreenState = SCREEN_STATE.LANDSCAPE_SCREEN;
		}

		// 状态设置
		updadeControlState();

		if ((mCurrentPlayType != FROM_LOCAL || mCurrentPlayType == FROM_LAST_PLAYED && URLUtil.isValidUrl(mUrl))
				&& NetUtil.isMobileActive(getApplicationContext())) {
			ShowRemandDialog(R.string.remind, R.string.net_error_info2, false, R.string.cancel_btn, R.string.go_on);
		}

		// 延时隐藏标题栏和控制栏
		mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, (int)(MSG_HIDE_CONTROL_BAR_DELAY * 1.5));

		// 打开视频
		mRefreshHandler.sendEmptyMessageDelayed(MSG_DELAYED_OPEN, MSG_DELAYED_OPEN_DELAY);
	}

	/**
	 * 设置标题
	 */
	private void setTitle() {
		switch (mCurrentPlayType) {
			case FROM_URL_INPUT :
				mTitleContorl.setTitle(mUrl.substring(mUrl.lastIndexOf("/") + 1));
				break;
			case FROM_LOCAL :
				mTitleContorl.setTitle(mCurrentLocalVideo.getDisplayName());
				break;
			case FROM_ARCLOULD :
				mTitleContorl.setTitle(mCurrentArclouldVideo.title);
				break;
			case FROM_LAST_PLAYED :
				mTitleContorl.setTitle(AcsPlayerApplication.getInstance().getSpUtil().getLastPlayedTitle());
			default :
				break;
		}
	}

	/**
	 * 更新状态
	 */
	private void updadeControlState() {
		// 状态设置
		int orientation = getResources().getConfiguration().orientation;
		mTitleContorl.setVRMode(orientation, mIsVRMode);
		mHDSelectControl.setState(mQualityState);
		mPlayControl.setQualityState(mQualityState);
		mPlayControl.setGyroState(mbGyroOpen);
	}

	/**
	 * 显示VR切换提示
	 */
	private void showVRSwitch() {
		TextView title = new TextView(this);
		title.setText(R.string.remind);
		title.setGravity(Gravity.CENTER);
		title.setTextSize(20);

		int messageId = 0;
		if (mIsVRMode) {
			messageId = R.string.bu_sure_to_exit_vr;
		} else {
			messageId = R.string.bu_sure_to_into_vr;
		}
		ShowRemandDialog(R.string.remind, messageId, false, R.string.cancel_btn, R.string.ok_btn);
//		new AlertDialog.Builder(this).setCustomTitle(title).setMessage(messageId)
//				.setPositiveButton(R.string.cancel_btn, new DialogInterface.OnClickListener() {
//
//					@Override
//					public void onClick(DialogInterface dialog, int arg1) {
//						dialog.dismiss();
//					}
//				}).setNegativeButton(R.string.ok_btn, new DialogInterface.OnClickListener() {
//
//					@Override
//					public void onClick(DialogInterface dialog, int arg1) {
//						dialog.dismiss();
//						mIsVRMode = !mIsVRMode;
//						if (mIsVRMode) {
//							toVRMode();
//						} else {
//							toNormalMode();
//						}
//						int orientation = getResources().getConfiguration().orientation;
//						mTitleContorl.setVRMode(orientation, mIsVRMode);
//					}
//				}).show();
	}

	/**
	 * 切换到vr模式
	 */
	private void toVRMode() {
		setVideoVisible(true);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		reloadUi();
		mRefreshHandler.sendEmptyMessageDelayed(MSG_DELAYED_OPEN, MSG_DELAYED_OPEN_DELAY);
	}

	/**
	 * 切换到普通模式
	 */
	private void toNormalMode() {
		setVideoVisible(true);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
		reloadUi();
		mRefreshHandler.sendEmptyMessageDelayed(MSG_DELAYED_OPEN, MSG_DELAYED_OPEN_DELAY);
	}

	/**
	 * 打开视频
	 *
	 * @param uri
	 * @throws IllegalArgumentException
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	private void openUri(Uri uri) throws IllegalArgumentException, IllegalStateException, IOException {
		if (uri.toString().startsWith("rtsp://"))
			openFileStr(uri.toString());
		else {
			String path = UriUtil.uriToFilePath(this, uri);
			Log.v(TAG, "Convert URI " + uri + " to: " + path);
			openFileStr(path);
		}
	}

	/**
	 * 打开视频
	 *
	 * @param str
	 * @throws IllegalArgumentException
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@SuppressLint("NewApi")
	private void openFileStr(String str) throws IllegalArgumentException, IllegalStateException, IOException {
		boolean bValid = false;
		if (mCurrentPlayType != FROM_LOCAL)
			bValid = UriUtil.isInputTextValid(str);
		//	if (!bValid && mCurrentPlayType != FROM_LOCAL) {
		//	ToastUtil.showShort(this, R.string.invalid_url);
		//	return;
		//} else
		{

			LogUtil.d(TAG, "Opening " + mUrl);

			mDuration = 0;

			mMediaPlayer.reset();

			String customidString = "";
			String contentidString = "";
			String sepratorString0 = "/";
			String sepratorString1 = "_";
			int index0 = mUrl.lastIndexOf(sepratorString0);
			int index1 = mUrl.indexOf(sepratorString1, index0 + 1);
			int index2 = mUrl.indexOf(sepratorString1, index1 + 1);
			if (index1 > index0) {
				customidString = mUrl.substring(index0 + 1, index1);
			}
			if (index2 > index1) {
				contentidString = mUrl.substring(index1 + 1, index2);
			}

			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("User-Agent", "ArcSoft Player/3.5");
			headers.put("Referer", "ArcSoft Sample Player");

			mMediaPlayer.setDataSource(mUrl, headers);

			mMediaPlayer.setUserInfo(MEDIAFILE.DRM_CUSTOM_ID, customidString);
			mMediaPlayer.setUserInfo(MEDIAFILE.DRM_CONTENT_ID, contentidString);

			LogUtil.d(TAG, "setOnBufferingUpdateListener");
			mMediaPlayer.setOnBufferingUpdateListener(mOnBufferUpateLister);

			LogUtil.d(TAG, "setOnCompletionListener");
			mMediaPlayer.setOnCompletionListener(mOnCompletionListener);

			LogUtil.d(TAG, "setOnPreparedListener");
			mMediaPlayer.setOnPreparedListener(mOnPreparedListener);

			LogUtil.d(TAG, "setOnVideoSizeChangedListener");
			m_bVideoSizeChanged = false;
			mMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);

			mMediaPlayer.setOnInfoListener(mOnInfoListener);

			mMediaPlayer.setOnErrorListener(mOnErrorListener);

			mMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);

			mMediaPlayer.setOnMessageListener(mOnMessageListener);

			// mMediaPlayer.setLooping(true);

			LogUtil.d(TAG, "setDisplay");
			if (!mIsVRMode) {
				SurfaceHolder sh = null;
				sh = m_surfaceView.getHolder();
				LogUtil.d(TAG, "setDisplay sh = " + sh);
				mMediaPlayer.setDisplay(sh);
			} else {
				m_TextureView.setMediaPlayer(mMediaPlayer);
			}
			//mMediaPlayer.setHardwareMode(true);
			mMediaPlayer.setBenchmark(2);

			// mMediaPlayer.setMode(ArcMediaPlayer.MEDIA_PLAYER_MODE_FORWARD,
			// 2);
			// mMediaPlayer.setConfig(MEDIAFILE.INITIAL_BUFFERTIME_ID, 5000);
			// mMediaPlayer.setConfig(MEDIAFILE.MAX_BUFFERTIME_ID, 50000);
			// mMediaPlayer.setConfig(MV2Config.MEDIAFILE.BUFFERING_TIMEOUT_ID,
			// 1800);

			mMediaPlayer.setConfig(ArcMediaPlayer.CONFIG_NETWORK_CONNECT_TIMEOUT, mConnectTimeout * 1000);
			mMediaPlayer.setConfig(ArcMediaPlayer.CONFIG_NETWORK_RECEIVE_TIMEOUT, mReceiveTimeout * 1000);
			mMediaPlayer.setConfig(ArcMediaPlayer.CONFIG_NETWORK_RECONNECT_COUNT, mReconnectCount);

			// set the rect to (0, 0)
			videoSizeChanged(mMediaPlayer, mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight());

			mMediaPlayer.prepareAsync();

			// set the real rect
			videoSizeChanged(mMediaPlayer, mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight());

			SystemUtil.controlBackLight(this, true);

			m_PlayerState = AMMF_STATE.PREPARING;

			LogUtil.d(TAG, "showOpenURLDlg 12");


		}
	}

	/**
	 * 得到当前URL
	 *
	 * @param currentPlayIndex
	 * @param qualityState
	 * @return
	 */
	private String getCurrentPlayUrl(int currentPlayIndex, String qualityState) {
		switch (mCurrentPlayType) {
			case FROM_URL_INPUT :
				;
				break;
			case FROM_LOCAL :
				mCurrentLocalVideo = mLocalVideoList.get(currentPlayIndex);
				mUrl = mCurrentLocalVideo.getPath();
				break;
			case FROM_ARCLOULD :
				mCurrentArclouldVideo = mArclouldVideoList.get(currentPlayIndex);
				ArrayList<TranscodedVideoInfo> transcodedVideoInfo = mCurrentArclouldVideo.transcodedVideoInfo;
				for (TranscodedVideoInfo videoInfo : transcodedVideoInfo) {
					if (qualityState.equals(videoInfo.name)) {
						mCurrentTranscodedVideoInfo = videoInfo;
						mUrl = videoInfo.hlsUrl;
						break;
					}
				}
				if (null == mUrl) {
					mCurrentTranscodedVideoInfo = transcodedVideoInfo.get(0);
					mUrl = transcodedVideoInfo.get(0).hlsUrl;
				}
				break;
			default :
				break;
		}
		return mUrl;
	}

	/**
	 * 停止播放
	 */
	private void stopPlayback() {
		if (m_PlayerState == AMMF_STATE.IDLE)
			return;

		mDuration = 0;
		mCurrentPosition = 0;
		m_PlayerState = AMMF_STATE.STOPPED;

		if (null != mMediaPlayer) {
			mMediaPlayer.stop();
		}

		if (mIsVRMode) {
			if (m_TextureView != null)
				m_TextureView.setMediaPlayer(null);
		}

		mRefreshHandler.removeMessages(MSG_GET_POSITION);
		mRefreshHandler.removeMessages(MSG_GET_BUFFERINGPERCENT);

		mPlayControl.setPlayState(m_PlayerState);
		mPlayControl.setCurrentPosition(mCurrentPosition);
		mPlayControl.setDuration(mDuration);

		SystemUtil.controlBackLight(this, false);

	}

	private ArcMediaPlayer.OnBufferingUpdateListener mOnBufferUpateLister = new ArcMediaPlayer.OnBufferingUpdateListener() {

		@Override
		public void onBufferingUpdate(ArcMediaPlayer mp, int percent) {
			;
		}
	};

	private ArcMediaPlayer.OnCompletionListener mOnCompletionListener = new ArcMediaPlayer.OnCompletionListener() {

		@Override
		public void onCompletion(ArcMediaPlayer mp) {
			LogUtil.d(TAG, "mOnCompletionListener");
			if (null != mMediaPlayer)
				mMediaPlayer.stop();
			m_PlayerState = AMMF_STATE.STOPPED;

			mPlayControl.setPlayState(m_PlayerState);
			mDuration = 0;
			mCurrentPosition = 0;
			mPlayControl.setCurrentPosition(mCurrentPosition);

			mRefreshHandler.removeMessages(MSG_GET_POSITION);
			mRefreshHandler.removeMessages(MSG_GET_BUFFERINGPERCENT);

			m_bVideoSizeChanged = false;
			SystemUtil.controlBackLight(PlayActivity.this, false);

			// playNext();
			mPlayAgainControl.setPlayAgainState(true);
		}
	};

	private ArcMediaPlayer.OnPreparedListener mOnPreparedListener = new ArcMediaPlayer.OnPreparedListener() {

		@Override
		public void onPrepared(ArcMediaPlayer mp) {
			LogUtil.d(TAG, "startPlayer mOnPreparedListener");
			m_PlayerState = AMMF_STATE.PREPARED;

			int duration = mMediaPlayer.getDuration();
			mDuration = duration;

			if (!m_bVideoSizeChanged)
				videoSizeChanged(mMediaPlayer, mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight());

			if (mCurrentPosition > 0) {
				mMediaPlayer.seekTo(mCurrentPosition);
			}

			m_PlayerState = AMMF_STATE.STARTED;
			mMediaPlayer.start();

			mRefreshHandler.sendEmptyMessage(MSG_GET_POSITION);

			mPlayControl.setDuration(mDuration);
			mPlayControl.setKeyProgressIncrement(SEEK_STEP);
			mPlayControl.setPlayState(m_PlayerState);

			if (mDuration >= 0) {
				AcsPlayerApplication.getInstance().getSpUtil().setLastPlayedUrl(mUrl);
				AcsPlayerApplication.getInstance().getSpUtil().setLastPlayedTitle(mTitleContorl.getTitle());

				if (mCurrentPlayType == FROM_URL_INPUT) {
					boolean bHave = false;
					for (InputVideoInfo info : mInputVideoInfoList) {
						if (mUrl.equals(info.getPath())) {
							bHave = true;
							break;
						}
					}
					if (!bHave) {
						InputVideoInfo videoInfo = new InputVideoInfo();
						videoInfo.setDisplayName(mTitleContorl.getTitle());
						videoInfo.setPath(mUrl);
						AcsPlayerApplication.getInstance().getDbHelper().addInputVideoInfo(videoInfo);
					}
				}
			}
		}
	};

	private ArcMediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener = new ArcMediaPlayer.OnVideoSizeChangedListener() {

		@Override
		public void onVideoSizeChanged(ArcMediaPlayer mp, int what, int extra) {
			videoSizeChanged(mp, what, extra);
		}
	};

	private ArcMediaPlayer.OnInfoListener mOnInfoListener = new ArcMediaPlayer.OnInfoListener() {

		@Override
		public boolean onInfo(ArcMediaPlayer mp, int what, int extra) {
			switch (what) {
				case android.media.MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING :
					LogUtil.e(TAG, "Bad interleaving of media file, audio/video are not well-formed, extra is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_BUFFERING_END :
					m_bBuffering = false;
					if (null != mLoadingDialog)
						mLoadingDialog.hide();
					mRefreshHandler.removeMessages(MSG_GET_BUFFERINGPERCENT);
					LogUtil.w(TAG, "Player is resuming playback after filling buffer, extra is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_BUFFERING_START :
					m_bBuffering = true;
					if (null != mLoadingDialog)
						mLoadingDialog.show();
					LogUtil.w(TAG, "Player is temporarily pausing playback internally to buffer more data, extra is " + extra);
					mRefreshHandler.sendEmptyMessage(MSG_GET_BUFFERINGPERCENT);
					break;
				case ArcMediaPlayer.MEDIA_INFO_METADATA_UPDATE :
					LogUtil.w(TAG, "A new set of metadata is available, extra is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_NOT_SEEKABLE :
					LogUtil.e(TAG, "The stream cannot be seeked, extra is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING :
					LogUtil.w(TAG, "It's too complex for the decoder, extra is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_UNKNOWN :
					LogUtil.w(TAG, "Unknown info, extra is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_RENDERING_START :
					LogUtil.w(TAG, "video decode succeeded, start rendering");
					break;
				// warnings definition below
				case ArcMediaPlayer.MEDIA_INFO_SPLITTER_NOAUDIO :
					LogUtil.e(TAG, "MEDIA_INFO_SPLITTER_NOAUDIO ,Info type is " + what + ", level is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_SPLITTER_NOVIDEO :
					LogUtil.e(TAG, "MEDIA_INFO_SPLITTER_NOVIDEO, Info type is " + what + ", level is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_VCODEC_UNSUPPORTVIDEO :
					Log.e(TAG, "MEDIA_INFO_VCODEC_UNSUPPORTVIDEO, Info type is " + what + ", level is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_ACODEC_UNSUPPORTAUDIO :
					Log.e(TAG, "MEDIA_INFO_ACODEC_UNSUPPORTAUDIO, Info type is " + what + ", level is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_VCODEC_DECODE_ERROR :
					LogUtil.e(TAG, "MEDIA_INFO_VCODEC_DECODE_ERROR, Info type is " + what + ", level is " + extra);
					break;
				case ArcMediaPlayer.MEDIA_INFO_ACODEC_DECODE_ERROR :
					LogUtil.e(TAG, "MEDIA_INFO_ACODEC_DECODE_ERROR, Info type is " + what + ", level is " + extra);
					break;
				default :
					LogUtil.i(TAG, "Unknown info code: " + what + ", extra is " + extra);
					break;
			}
			return true;
		}
	};

	private int mRetryCount = 0;
	private int mRetryLimit = 3;
	private ArcMediaPlayer.OnErrorListener mOnErrorListener = new ArcMediaPlayer.OnErrorListener() {
		boolean bUpdate = false;
		boolean bNeedRetry = false;
		int lastPlayedPosition = 0;
		String codecTypeString = "";

		@Override
		public boolean onError(ArcMediaPlayer mp, int what, int extra) {
			switch (what) {
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_UNSUPPORTED_SCHEME :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_SOURCE_UNSUPPORTED_SCHEME, value = " + what);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_STREAM_SEEK :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_SOURCE_STREAM_SEEK, value = " + what);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_DNS_RESOLVE :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_SOURCE_DNS_RESOLVE, value = " + what);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_PLAYER_DISPLAY_INIT_FAILED :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_PLAYER_DISPLAY_INIT_FAILED, value = " + what);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_PLAYER_NOAUDIO_VIDEOUNSUPPORT :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_PLAYER_NOAUDIO_VIDEOUNSUPPORT, value = " + what);
					codecTypeString = mMediaPlayer.getMediaMetadata(MV2Config.METADATA.METADATA_KEY_VIDEO_TYPE, bUpdate);
					Log.e(TAG, "onError: unsupproted video codec is " + codecTypeString);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_PLAYER_NOVIDEO_AUDIOUNSUPPORT :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_PLAYER_NOVIDEO_AUDIOUNSUPPORT, value = " + what);
					codecTypeString = mMediaPlayer.getMediaMetadata(MV2Config.METADATA.METADATA_KEY_AUDIO_TYPE, bUpdate);
					Log.e(TAG, "onError: unsupproted audio codec is " + codecTypeString);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_PLAYER_AVCODEC_UNSUPPORT :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_PLAYER_AVCODEC_UNSUPPORT, value = " + what);
					codecTypeString = mMediaPlayer.getMediaMetadata(MV2Config.METADATA.METADATA_KEY_VIDEO_TYPE, bUpdate);
					Log.e(TAG, "onError: unsupproted video codec is " + codecTypeString);
					codecTypeString = mMediaPlayer.getMediaMetadata(MV2Config.METADATA.METADATA_KEY_AUDIO_TYPE, bUpdate);
					Log.e(TAG, "onError: unsupproted audio codec is " + codecTypeString);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_PLAYER_AVCODEC_AUDIOUNSUPPORT :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_PLAYER_AVCODEC_AUDIOUNSUPPORT, value = " + what);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_PLAYER_AVCODEC_VIDEOUNSUPPORT :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_PLAYER_AVCODEC_VIDEOUNSUPPORT, value = " + what);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_PLAYER_OPERATION_CANNOTEXECUTE :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_PLAYER_OPERATION_CANNOTEXECUTE, value = " + what);
					break;
				case android.media.MediaPlayer.MEDIA_ERROR_UNKNOWN :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_UNKNOWN, value = " + what);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_SEEK_BEYONDFILESIZE :
					Log.e(TAG, "onError: error type is MEDIA_ERROR_SOURCE_SEEK_BEYONDFILESIZE, value = " + what);
					break;
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_NETWORK_CONNECTFAIL :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_STREAM_OPEN :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_DATARECEIVE_TIMEOUT :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_FORMAT_UNSUPPORTED :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_FORMAT_MALFORMED :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_NETWORK_CONNECTIMEOUT :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_DATARECEIVE_FAIL :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_DATASEND_TIMEOUT :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_DATAERROR_HTML :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_DATASEND_FAIL :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_DATARECEIVE_NOBODY :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_DNS_RESOLVE_TIMEOUT :
				case ArcMediaPlayer.MEDIA_ERROR_SOURCE_BUFFER_TIMEOUT :
					lastPlayedPosition = mp.getCurrentPosition();
					bNeedRetry = true;
					break;
				default :
					if (what >= 100400 && what <= 100599) {
						Log.e(TAG, "onError: error type is one of the http critical status code, value = " + what);
					} else {
						Log.e(TAG, "onError: what the Fxxxx!! error is " + what + "? code is " + extra);
					}
					break;
			}
			stopPlayback();
			//ToastUtil.showShort(PlayActivity.this, "Error code = " + what + ", extra = " + extra);

			if (bNeedRetry)
				retryPlayback(lastPlayedPosition);

			return true;
		}
	};

	/**
	 * 重试机制
	 *
	 * @param lastPos
	 */
	private void retryPlayback(int lastPos) {
		if (mRetryCount++ < mRetryLimit) {
			if (mMediaPlayer != null) {
				mMediaPlayer.reset();
				mMediaPlayer.release();
				mMediaPlayer = null;
			}

			mMediaPlayer = new ArcMediaPlayer();
			mMediaPlayer.setConfigFile(this, getFilesDir().getAbsolutePath() + "/MV3Plugin.ini");

			try {
				openFileStr(mUrl);
			} catch (Exception e) {
				e.printStackTrace();
				//ToastUtil.showShort(PlayActivity.this, "重试出错");
			}
		} else {
			//ToastUtil.showShort(PlayActivity.this, "达到重试次数上限");
			ShowRemandDialog(R.string.remind, R.string.invalid_url2);
		}
	}

	private ArcMediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener = new ArcMediaPlayer.OnSeekCompleteListener() {

		@Override
		public void onSeekComplete(ArcMediaPlayer mp) {
			LogUtil.d(TAG, "onSeekComplete, new position: " + mp.getCurrentPosition() + "ms");
		}
	};

	private ArcMediaPlayer.onMessageListener mOnMessageListener = new ArcMediaPlayer.onMessageListener() {

		@Override
		public boolean onMessage(ArcMediaPlayer mp, int messageInfo, int level) {
			switch (messageInfo) {
				default :
					LogUtil.e(TAG, "unknown messageInfo  is " + messageInfo + ", level is " + level);
					break;
			}
			return true;
		}
	};

	/**
	 * 显示提示对话框
	 */
	private void ShowRemandDialog(int titleId, int messageId, boolean isRemand, int leftButtonId, int rigthButtonId) {
		if (null != mRemandDialog && mRemandDialog.isShowing())
			mRemandDialog.hide();
		try {
			switch (messageId) {
				case R.string.net_error_info :
				case R.string.net_error_info2 :
					mDialogType = NormalDialog.DIALOG_WIFI_ERROR;
					break;
				case R.string.bu_sure_to_exit_vr:
				case R.string.bu_sure_to_into_vr:
					mDialogType = NormalDialog.DIALOG_VR;
					break;
				case R.string.be_sure_to_exit :
					mDialogType = NormalDialog.DIALOG_EXIT_APP;
					break;
				default :
					mDialogType = NormalDialog.DIALOG_NONE;
					break;
			}

//			TextView title = new TextView(this);
//			title.setText(titleId);
//			title.setGravity(Gravity.CENTER);
//			title.setTextSize(20);
//			mRemandDialog = new AlertDialog.Builder(this/*
//														 * ,
//														 * R.style.normalDialog
//														 */).setCustomTitle(title).setMessage(messageId)
//					.setPositiveButton(leftButtonId, new DialogInterface.OnClickListener() {
//
//						@Override
//						public void onClick(DialogInterface dialog, int arg1) {
//							dialog.dismiss();
//							PlayActivity.this.finish();
//						}
//					}).setNegativeButton(rigthButtonId, new DialogInterface.OnClickListener() {
//
//						@Override
//						public void onClick(DialogInterface dialog, int arg1) {
//							dialog.dismiss();
//
//							// 延时隐藏标题栏和控制栏
//							mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_HIDE_POP_BAR_DELEY);
//							// 打开视频
//							mRefreshHandler.sendEmptyMessageDelayed(MSG_DELAYED_OPEN, MSG_DELAYED_OPEN_DELAY);
//						}
//					}).show();

			if (leftButtonId > 0 && rigthButtonId > 0) {
				mRemandDialog = new NormalDialog(this, R.style.no_title_dilog, titleId, messageId, isRemand, leftButtonId, rigthButtonId,
						mRemandClickListener);
			} else {
				mRemandDialog = new NormalDialog(this, R.style.no_title_dilog, titleId, messageId, isRemand, mRemandClickListener);
			}
			mRemandDialog.show();
			WindowManager windowManager = getWindowManager();
			Display display = windowManager.getDefaultDisplay();
			WindowManager.LayoutParams lp = mRemandDialog.getWindow().getAttributes();
			if (mScreenState == SCREEN_STATE.LANDSCAPE_SCREEN) {
				lp.height = (int) (display.getHeight() * 0.55); // 高度设置为屏幕的0.3
				lp.width = (int) (display.getWidth() * 0.6); // 宽度设置为屏幕的0.5
			} else if (mScreenState == SCREEN_STATE.PORTRAIT_SCREEN) {
				lp.height = (int) (display.getHeight() * 0.35); // 高度设置为屏幕的0.3
				lp.width = (int) (display.getWidth() * 0.8); // 宽度设置为屏幕的0.5
			}
			mRemandDialog.getWindow().setAttributes(lp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private NormalDialog.ClickListener mRemandClickListener = new NormalDialog.ClickListener() {

		@Override
		public void confirm() {
			mRemandDialog.dismiss();
			switch (mDialogType) {
				case NormalDialog.DIALOG_NONE :
					break;
				case NormalDialog.DIALOG_EXIT_APP :
					finish();
					break;
				case NormalDialog.DIALOG_WIFI_ERROR :
					// 延时隐藏标题栏和控制栏
					mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_HIDE_POP_BAR_DELEY);
					// 打开视频
					mRefreshHandler.sendEmptyMessageDelayed(MSG_DELAYED_OPEN, MSG_DELAYED_OPEN_DELAY);
					break;
				case NormalDialog.DIALOG_VR:
					mIsVRMode = !mIsVRMode;
					if (mIsVRMode) {
						toVRMode();
					} else {
						toNormalMode();
					}
					int orientation = getResources().getConfiguration().orientation;
					mTitleContorl.setVRMode(orientation, mIsVRMode);
				default :
					break;
			}
		}

		@Override
		public void cancel() {
			mRemandDialog.dismiss();
			switch (mDialogType) {
				case NormalDialog.DIALOG_NONE :
					break;
				case NormalDialog.DIALOG_EXIT_APP :
					break;
				case NormalDialog.DIALOG_WIFI_ERROR :
					PlayActivity.this.finish();
					break;
				case NormalDialog.DIALOG_VR :
					break;
				default :
					break;
			}
		}

		@Override
		public void remand() {
			mRemandDialog.dismiss();
		}

	};

	/** 播控相关 */
	protected Handler mRefreshHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_DELAYED_OPEN_EXT :
					try {
						openUri(m_uri);
					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
				case MSG_DELAYED_OPEN :
					try {
						openFileStr(getCurrentPlayUrl(mCurrentPlayIndex, mQualityState));
					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
				case MSG_GET_POSITION : {
					mRefreshHandler.removeMessages(MSG_GET_POSITION);
					if (null != mMediaPlayer && mMediaPlayer.isPlaying()) {
						try {
							mCurrentPosition = mMediaPlayer.getCurrentPosition();
						} catch (IllegalStateException e) {
							// stop getting position
							break;
						}

						if (!mPlayControl.getSeekBar().isPressed() && m_PlayerState != AMMF_STATE.PAUSED && !m_bBuffering) {
							mPlayControl.setCurrentPosition(mCurrentPosition);
						}
					}

					mRefreshHandler.sendEmptyMessageDelayed(MSG_GET_POSITION, MSG_DELAYED_OPEN_DELAY);
				}
				break;
				case MSG_GET_BUFFERINGPERCENT : {
					mRefreshHandler.removeMessages(MSG_GET_BUFFERINGPERCENT);

					int nCurPercent = 0;
					if (null != mMediaPlayer) {
						try {
							nCurPercent = mMediaPlayer.getCurrentBufferingPercent();
						} catch (IllegalStateException e) {
							// stop getting position
							break;
						}
						// buffering
						mRefreshHandler.sendEmptyMessageDelayed(MSG_GET_BUFFERINGPERCENT, 300);
					}
				}
				break;
			}
		}
	};

	private class PlayGestureListener extends SimpleOnGestureListener {

		@Override
		public boolean onDown(MotionEvent e) {
			if (mIsVRMode) {
				if (mPlayControl.isShown())
					mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
				return false;
			}

			mbFirstScroll = true;
			mGestureCurrentPosition = mCurrentPosition;
			LogUtil.d(TAG, "GESTURE_MODIFY_PROGRESS mGestureCurrentPosition = " + mCurrentPosition);
			if (mPlayControl.isShown())
				mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
			return false;
		}

		/** 双击 */
		@Override
		public boolean onDoubleTap(MotionEvent e) {

			return true;
		}

		/** 滑动 */
		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
			if (mIsVRMode)
				return false;

			float mOldX = e1.getX(), mOldY = e1.getY();
			int y = (int) e2.getRawY();
			LogUtil.d(TAG, "distanceX = " + distanceX + "distanceY = " + distanceY);
			if (mbFirstScroll) {// 以触摸屏幕后第一次滑动为标准，避免在屏幕上操作切换混乱
				// 横向的距离变化大则调整进度，纵向的变化大则调整音量
				if (Math.abs(distanceX) - Math.abs(distanceY) > MIN_DISTANCE) {
					mGestureTag = GESTURE_MODIFY_PROGRESS;
					if (checkPopBar())
						mbGestrueProgress = true;
				} else if (Math.abs(distanceY) - Math.abs(distanceX) > MIN_DISTANCE) {
					if (mOldX < mWindowWidth * 2.0 / 5) {// 音量
						mGestureTag = GESTURE_MODIFY_VOLUME;
						if (checkPopBar())
							mbGestrueVolume = true;
					} else if (mOldX > mWindowWidth * 3.0 / 5) {// 亮度
						mGestureTag = GESTURE_MODIFY_BRIGHT;
						if (checkPopBar())
							mbGestrueBright = true;
					}
				}
			}
			LogUtil.d(TAG, "onScroll : mGestureTag = " + mGestureTag);
			switch (mGestureTag) {
				case GESTURE_MODIFY_PROGRESS :
					if (!mbGestrueProgress)
						break;
					if (Math.abs(distanceX) > Math.abs(distanceY)) {// 横向移动大于纵向移动
						if (!mFastMoveControl.isShown()) {
							mFastMoveControl.show();
						}
						mRefreshHandler.removeMessages(MSG_GET_POSITION);
						if (distanceX >= DensityUtil.dip2px(getApplicationContext(), STEP_PROGRESS)) {// 快退，用步长控制改变速度，可微调
							// mPlayControl.decrease();
							if (mGestureCurrentPosition > 0) {// 避免为负
								mGestureCurrentPosition -= 1000;// scroll方法执行一次快退1秒
							} else {
								mGestureCurrentPosition = 0;
							}
							mFastMoveControl.update(FastMoveView.STATE_BACKWORD);
							mFastMoveControl.setPostion(mGestureCurrentPosition, mDuration);
						} else if (distanceX <= -DensityUtil.dip2px(getApplicationContext(), STEP_PROGRESS)) {// 快进
							// mPlayControl.increase();
							if (mGestureCurrentPosition < mDuration - 16000) {// 避免超过总时长
								mGestureCurrentPosition += 1000;// scroll执行一次快进1秒
							} else {
								mGestureCurrentPosition = mDuration - 10000;
							}
							mFastMoveControl.update(FastMoveView.STATE_FORWORD);
							mFastMoveControl.setPostion(mGestureCurrentPosition, mDuration);
						}
					}

					break;
				case GESTURE_MODIFY_VOLUME :
					if (!mbGestrueVolume)
						break;
					if (Math.abs(distanceY) > Math.abs(distanceX)) {// 纵向移动大于横向移动
						if (!mVolumeControl.isShown()) {
							mVolumeControl.show();
						}
						if (distanceY >= DensityUtil.dip2px(getApplicationContext(), STEP_VOLUME)) {// 音量调大
							mVolumeControl.increase();
						} else if (distanceY <= -DensityUtil.dip2px(getApplicationContext(), STEP_VOLUME)) {// 音量调小
							mVolumeControl.decrease();
						}
					}

					break;
				case GESTURE_MODIFY_BRIGHT :
					if (!mbGestrueBright)
						break;
					if (Math.abs(distanceY) > Math.abs(distanceX)) {// 纵向移动大于横向移动
						if (!mBrihtnessControl.isShown()) {
							mBrihtnessControl.show();
						}
						if (distanceY >= DensityUtil.dip2px(getApplicationContext(), STEP_BRIGHT)) {// 亮度调大
							mBrihtnessControl.increase();
						} else if (distanceY <= -DensityUtil.dip2px(getApplicationContext(), STEP_BRIGHT)) {// 亮度调小
							mBrihtnessControl.decrease();
						}
					}
					break;

				default :
					break;
			}
			return super.onScroll(e1, e2, distanceX, distanceY);
		}

	}

	/**
	 * 手势结束
	 *
	 */
	private void endGesture() {
		// 隐藏
		mDismissHandler.removeMessages(MSG_HIDE_POP_BAR);
		mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_POP_BAR, 500);
	}

	/**
	 * 定时隐藏
	 *
	 */
	private Handler mDismissHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_HIDE_CONTROL_BAR :
					mTitleContorl.hide();
					mPlayControl.hide();
					mbGestruePlay = false;
					break;
				case MSG_SHOW_CONTROL_BAR :
					mPlayControl.show();
					mTitleContorl.show();
					mbGestruePlay = true;
					removeMessages(MSG_HIDE_CONTROL_BAR);
					sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_HIDE_CONTROL_BAR_DELAY);
					break;
				case MSG_HIDE_POP_BAR :
					resetPopBar();
					break;
				default :
					break;
			}
		}
	};

	private TitleInterface mTitleInterface = new TitleInterface() {

		@Override
		public void clickLeft() {
			BrightnessView.startAutoBrightness(getApplicationContext());
			stopPlayback();
			finish();
		}

		@Override
		public void clickMiddel() {
			// 弹出VR提示
			showVRSwitch();
			// if (mIsVRMode) {
			// ShowRemandDialog(R.string.remind, R.string.bu_sure_to_exit_vr,
			// false, R.string.cancel_btn,
			// R.string.ok_btn);
			// } else {
			// ShowRemandDialog(R.string.remind, R.string.bu_sure_to_into_vr,
			// false, R.string.cancel_btn,
			// R.string.ok_btn);
			// }
		}

		@Override
		public void clickRight() {
			// VR模式 打开快进快退开关
			if (mIsVRMode) {
				if (checkPopBar())
					mbGestrueProgress = true;
				if (!mbGestrueProgress)
					return;
				if (!mFastMoveControl.isShown()) {
					mFastMoveControl.setPostion(mCurrentPosition, mDuration);
					mFastMoveControl.show();
					mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_POP_BAR, MSG_HIDE_POP_BAR_DELEY2);
				} else {
					mFastMoveControl.hide();
				}
			} else {
				// 普通模式 打开/关闭陀螺仪开关控件
				if (checkPopBar())
					mbGestrueGyroHD = true;
				if (!mbGestrueGyroHD)
					return;
				if (!mGyroHDControl.isShown()) {
					mGyroHDControl.show();
				} else {
					mGyroHDControl.hide();
				}
			}
		}

	};

	private SelectInterface mSelectInterface = new SelectInterface() {

		@Override
		public void setState(String state) {
			mQualityState = state;
			mPlayControl.setQualityState(mQualityState);
			getCurrentPlayUrl(mCurrentPlayIndex, mQualityState);
			try {
				int currentpositon = mCurrentPosition;
				stopPlayback();
				mCurrentPosition = currentpositon;
				openFileStr(mUrl);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	};

	private FastMoveInterface mFaceMoveInterface = new FastMoveInterface() {

		@Override
		public void clickControlGyro() {
			// 陀螺仪开关
			mbGyroOpen = !mbGyroOpen;
			mGyroHDControl.hide();
		}

		@Override
		public void clickControlHD() {
			// 画质选择
			mGyroHDControl.hide();
			mbGestrueGyroHD = false;
			if (checkPopBar())
				mbGestrueHDSelect = true;
			if (!mbGestrueHDSelect)
				return;
			if (!mHDSelectControl.isShown()) {
				mHDSelectControl.show();
			} else {
				mHDSelectControl.hide();
			}
		}

		@Override
		public void clickControlFastFroward() {
			mRefreshHandler.removeMessages(MSG_GET_POSITION);
			if (mCurrentPosition < mDuration - 16000) {// 避免超过总时长
				mCurrentPosition += 5000;// scroll执行一次快进5秒
			} else {
				mCurrentPosition = mDuration - 10000;
			}
			mFastMoveControl.update(FastMoveView.STATE_BACKWORD);
			mFastMoveControl.setPostion(mCurrentPosition, mDuration);
			mMediaPlayer.seekTo(mCurrentPosition);
			mRefreshHandler.sendEmptyMessage(MSG_GET_POSITION);

			mDismissHandler.removeMessages(MSG_HIDE_POP_BAR);
			mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_POP_BAR, MSG_HIDE_POP_BAR_DELEY2);
		}

		@Override
		public void clickControlFastBackward() {
			mRefreshHandler.removeMessages(MSG_GET_POSITION);
			if (mCurrentPosition > 5000) {// 避免为负
				mCurrentPosition -= 5000;// scroll方法执行一次快退5秒
			} else {
				mCurrentPosition = 0;
			}
			mFastMoveControl.update(FastMoveView.STATE_BACKWORD);
			mFastMoveControl.setPostion(mCurrentPosition, mDuration);
			mMediaPlayer.seekTo(mCurrentPosition);
			mRefreshHandler.sendEmptyMessage(MSG_GET_POSITION);

			mDismissHandler.removeMessages(MSG_HIDE_POP_BAR);
			mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_POP_BAR, MSG_HIDE_POP_BAR_DELEY2);
		}

	};

	private PlayControlInterface mPlayControlInterface = new PlayControlInterface() {

		@Override
		public void clickPlay() {
			switch (m_PlayerState) {
				case IDLE :
					LogUtil.d(TAG, "onClick,but_open:begin");
					setVideoVisible(false);
					LogUtil.d(TAG, "onClick,but_open:End");
					break;
				case STARTED :
					KeepScreenOn(true);
					LogUtil.d(TAG, "onClick,but_pause:begin");
					m_PlayerState = AMMF_STATE.PAUSED;
					mMediaPlayer.pause();
					mPlayControl.setPlayState(m_PlayerState);
					LogUtil.d(TAG, "onClick,but_pause:end");
					break;
				case STOPPED :
					KeepScreenOn(false);
					LogUtil.d(TAG, "onClick,but_play:begin");
					mDuration = 0;
					m_PlayerState = AMMF_STATE.IDLE;
					if (mMediaPlayer != null)
						mMediaPlayer.reset(); // reset should be idle status,not
					// stop
					setVideoVisible(false);
					LogUtil.d(TAG, "onClick,but_play:end");
					break;
				case PAUSED :
					LogUtil.d(TAG, "onClick,but_play:begin");
					mMediaPlayer.start();
					m_PlayerState = AMMF_STATE.STARTED;
					mPlayControl.setPlayState(m_PlayerState);
					LogUtil.d(TAG, "onClick,but_play:end");
					break;
				default :
					break;
			}
			if (mbGestruePlay) {
				mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
				mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_HIDE_CONTROL_BAR_DELAY);
			}
		}

		@Override
		public void clickNext() {
			playNext();
			if (mbGestruePlay) {
				mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
				mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_HIDE_CONTROL_BAR_DELAY);
			}
		}

		@Override
		public void clickDual() {
			// TODO 切换VR模式下 双眼模式
			if (mIsVRMode) {
				mbDualOpen = !mbDualOpen;
				mPlayControl.setDualState(mbDualOpen);
				switchVRMode();
			}
			if (mbGestruePlay) {
				mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
				mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_HIDE_CONTROL_BAR_DELAY);
			}
		}

		@Override
		public void clickGyro() {
			// TODO 切换VR模式下陀螺仪开关
			if (mIsVRMode) {
				mbGyroOpen = !mbGyroOpen;
				mPlayControl.setGyroState(mbGyroOpen);
				switchVRMode();
			}
			if (mbGestruePlay) {
				mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
				mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_HIDE_CONTROL_BAR_DELAY);
			}
		}

		@Override
		public void clickHD() {
			// 画质选择
			mGyroHDControl.hide();
			mbGestrueGyroHD = false;
			if (checkPopBar())
				mbGestrueHDSelect = true;
			if (!mbGestrueHDSelect)
				return;
			if (!mHDSelectControl.isShown()) {
				mHDSelectControl.show();
			} else {
				mHDSelectControl.hide();
			}
			if (mbGestruePlay) {
				mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
				mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_HIDE_CONTROL_BAR_DELAY);
			}
		}

		@Override
		public void clickFullScreen() {
			// 横竖屏切换
			mScreenState = getScreenState();
			if (mScreenState == SCREEN_STATE.LANDSCAPE_SCREEN) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
				mPlayControl.setScreenState(SCREEN_STATE.PORTRAIT_SCREEN);
			} else if (mScreenState == SCREEN_STATE.PORTRAIT_SCREEN) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
				mPlayControl.setScreenState(SCREEN_STATE.LANDSCAPE_SCREEN);
			}
			if (mbGestruePlay) {
				mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
				mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_HIDE_CONTROL_BAR_DELAY);
			}
		}

		@Override
		public void clickSeek(int currentPosition) {
			// seek
			mCurrentPosition = currentPosition;
			mMediaPlayer.seekTo(mCurrentPosition);
			if (mPlayControl.isShown())
				mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);

			if (mbGestruePlay) {
				mDismissHandler.removeMessages(MSG_HIDE_CONTROL_BAR);
				mDismissHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROL_BAR, MSG_HIDE_CONTROL_BAR_DELAY);
			}
		}

	};

	private PlayAgainControlInterface mPlayAgainControlInterface = new PlayAgainControlInterface() {

		@Override
		public void clickPlayAgain() {
			try {
				mPlayAgainControl.setPlayAgainState(false);
				stopPlayback();
				setVideoVisible(true);
				openFileStr(mUrl);
				setTitle();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	};

	/**
	 * 得到当前屏幕状态(横屏/竖屏)
	 *
	 * @return
	 */
	private SCREEN_STATE getScreenState() {
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			return SCREEN_STATE.LANDSCAPE_SCREEN;
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
			return SCREEN_STATE.PORTRAIT_SCREEN;
		}
		return SCREEN_STATE.PORTRAIT_SCREEN;
	}

	/**
	 * 显示/隐藏surface
	 *
	 * @param visible
	 */
	private void setVideoVisible(boolean visible) {
		if (mIsVRMode) {
			m_TextureView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
			m_surfaceView.setVisibility(!visible ? View.VISIBLE : View.INVISIBLE);
		} else {
			m_surfaceView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
			m_TextureView.setVisibility(!visible ? View.VISIBLE : View.INVISIBLE);
		}
	}

	/**
	 * 播放下一个视频
	 */
	private void playNext() {
		switch (mCurrentPlayType) {
			case FROM_URL_INPUT :
				break;
			case FROM_LOCAL :
				if (mCurrentPlayIndex < mLocalVideoList.size()) {
					mCurrentPlayIndex++;
				} else {
					mCurrentPlayIndex = 0;
				}

				try {
					stopPlayback();
					openFileStr(getCurrentPlayUrl(mCurrentPlayIndex, mQualityState));
					setTitle();
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case FROM_ARCLOULD :
				if (mCurrentPlayIndex < mArclouldVideoList.size()) {
					mCurrentPlayIndex++;
				} else {
					mCurrentPlayIndex = 0;
				}
				try {
					stopPlayback();
					openFileStr(getCurrentPlayUrl(mCurrentPlayIndex, mQualityState));
					setTitle();
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			default :
				break;
		}
	}

	/**
	 * VR模式相关
	 */
	class ModeCombination {
		RenderMode renderMode;
		ControlMode ctrlMode;
		int txtLabel;
		public ModeCombination(RenderMode m, ControlMode c, int l) {
			renderMode = m;
			ctrlMode = c;
			txtLabel = l;
		}
	};
	ModeCombination mModes[] = {new ModeCombination(RenderMode.NORMALVIEW, ControlMode.TOUCH, R.string.mode_normal),
			new ModeCombination(RenderMode.NORMALVIEW3DHALF, ControlMode.TOUCH, R.string.mode_normal_3d),
			new ModeCombination(RenderMode.FULLVIEW, ControlMode.TOUCH, R.string.mode_touch_vr),
			new ModeCombination(RenderMode.FULLVIEW3D, ControlMode.TOUCH, R.string.mode_touch_3d),
			new ModeCombination(RenderMode.FULLVIEW, ControlMode.GYROSCOPE, R.string.mode_gyro_vr),
			new ModeCombination(RenderMode.FULLVIEW3D, ControlMode.GYROSCOPE, R.string.mode_gyro_3d)};

	int miCurrentMode = 2;
	RenderMode mRenderMode = RenderMode.FULLVIEW;
	ControlMode mControlMode = ControlMode.GYROSCOPE;

	/**
	 * VR模式切换
	 */
	void switchVRMode() {
		if (mbDualOpen) {
			mRenderMode = RenderMode.FULLVIEW3D;
		} else {
			mRenderMode = RenderMode.FULLVIEW;
		}

		if (mbGyroOpen) {
			mControlMode = ControlMode.GYROSCOPE;
		} else {
			mControlMode = ControlMode.TOUCH;
		}
		m_TextureView.setRenderMode(mRenderMode);
		m_TextureView.setControlMode(mControlMode);
	}

	void onSwitchVRMode(boolean bReverse) {
		int nextMode = 0;

		if (!mIsVRMode || !m_TextureView.isMotionSensorPresent()) {
			nextMode = miCurrentMode + (bReverse ? -1 : 1);
			nextMode = (nextMode + 4) % 4;
		} else {
			nextMode = miCurrentMode + (bReverse ? -1 : 1);
			nextMode = (nextMode + mModes.length) % mModes.length;
		}
		Log.d(TAG, "switchVRMode bReverse = " + bReverse + ", mRenderMode = " + mRenderMode + ", newRenderMode = "
				+ mModes[nextMode].renderMode);
		if (mRenderMode != mModes[nextMode].renderMode) {
			mRenderMode = mModes[nextMode].renderMode;
			m_TextureView.setRenderMode(mRenderMode);
		}

		if (mControlMode != mModes[nextMode].ctrlMode) {
			mControlMode = mModes[nextMode].ctrlMode;
			m_TextureView.setControlMode(mControlMode);
		}
		miCurrentMode = nextMode;
	}

	private GyroHDControlInterface mGyroHDControlInterface = new GyroHDControlInterface() {

		@Override
		public void clickControlGyro() {
			// TODO Auto-generated method stub
			// 陀螺仪开关
			mbGyroOpen = !mbGyroOpen;
			mGyroHDControl.hide();
		}

		@Override
		public void clickControlHD() {
			// TODO Auto-generated method stub
			mGyroHDControl.hide();
			mbGestrueGyroHD = false;
			if (checkPopBar())
				mbGestrueHDSelect = true;
			if (!mbGestrueHDSelect)
				return;
			if (!mHDSelectControl.isShown()) {
				mHDSelectControl.show();
			} else {
				mHDSelectControl.hide();
			}
		}
	};


}